<template>
    <div :style="{height:divHeight + 'px',overflow:'hidden',display:'flex',flexDirection:'row'}">
        <Menu @on-select="selectMenu" active-name="1">
            <Submenu name="1">
                <template #title>
                    <Icon type="ios-clock-outline" />
                    最近浏览
                </template>
                <MenuItem v-for="(item,index) in recentlyVieweds" :name="'1_'+index">{{item.fileName}}</MenuItem>
            </Submenu>
            <MenuItem name="2"><Icon type="md-folder" />资料列表</MenuItem>
            <Submenu name="3">
                <template #title>
                    <Icon type="md-star" />
                    我的收藏
                </template>
                <MenuItem v-for="(item,index) in collectionFiles" :name="'3_'+index">{{item.fileName}}</MenuItem>
            </Submenu>
        </Menu>
        <div style="display:flex;flex-direction: column;flex:auto">
            <Col span="24">
                <span class="navigationClass" v-for="(item,index) in levelArray" @click="toLevelItem(index)">{{item.title}}<Icon type="ios-arrow-forward" /></span>
                <div style="float: right">
                    <Button class="ivu-btn-reset" style="margin-right:20px" v-if="filePath && !isCollected" :loading="fileLoading" @click="addFileToCollection">添加收藏</Button>
                    <Button class="ivu-btn-reset" style="margin-right:20px" v-if="filePath && isCollected" :loading="fileLoading" @click="removeFileToCollection">取消收藏</Button>
                    <Button class="ivu-btn-reset" @click="returnTo">返回</Button>
                </div>
            </Col>
            <iframe v-if="filePath" :name="fileName" :src="filePath" style="margin-top:10px;width: 100%;text-align:center;height:100%"></iframe>
            <div v-else>
                <Spin v-if="loading" style="margin-top:300px">
                    <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
                    <div>Loading</div>
                </Spin>
                <Row v-else :gutter=16 style="margin-top:10px;">
                    <Col span="4" v-for="col in currentNodeArray.length" >
                        <div class="trainingDivClass" @click="enterDir(currentNodeArray[col-1])">
                            <img src="../../../../assets/img/dir.png" style="height:100px;width:100px"/>
                            <p class="titleClass">{{currentNodeArray[col-1].title}}</p>
                        </div>
                    </Col>
                    <Col span="4" v-for="col in pdfDatas.length" >
                        <div class="trainingDivClass" @click="enterPdf(pdfDatas[col-1])">
                            <img src="../../../../assets/img/pdf.jpg"  style="height:100px;width:100px"/>
                            <p class="titleClass">{{pdfDatas[col-1].fileName}}</p>
                        </div>
                    </Col>
                    <Col span="4" v-for="col in videoDatas.length" >
                        <div class="trainingDivClass" @click="enterVideo(videoDatas[col-1])">
                            <img src="../../../../assets/img/online_video.jpg"  style="height:100px;width:100px"/>
                            <p class="titleClass">{{videoDatas[col-1].fileName}}</p>
                        </div>
                    </Col>
                </Row>
            </div>
        </div>
    </div>
</template>
<script>
    import {Api} from '@/api/index.js'
    var cascaderDom = () => import('@/components/cascader-dom.vue');
    import {sessionStorage, cookie} from '@/common/cacheUtils.js';
    import pageCommonFunction from '@/components/pageCommonFunction.js'
    export default {
        data() {
            return {
                isCollected:false,
                fileLoading:false,
                loading:true,
                collectionFiles:[],
                recentlyVieweds:[],
                pdfDatas:[],
                videoDatas:[],
                divHeight:0,
                collectedId:"",
                fileId:"",
                filePath:"",
                fileName:"",
                levelArray:[{
                    title:"资料列表",
                    categoryId:"0",
                    parentId:"0"
                }],
                treeData:[{
                    categoryId : '0',
                    title : '培训资料',
                    parentId:'-1',
                    seq: 1,
                    children: []
                }],
                currentNodeArray:[],
                parentId:0,
            }
        },
        async mounted() {
            this.divHeight = window.innerHeight - 120;
            let queryMap = this.$route.query;
            if (queryMap && queryMap.parentId) {
                await this.enterDir(queryMap);
            }else {
                await this.queryTree(this.treeData[0]);
                this.currentNodeArray = this.treeData[0].children;
            }
            this.queryFileToCollection();
        },
        methods:{
            async queryTree(node) {
                await this.$http
                    .get(Api.trainingCategory, { params: { parentId: node.categoryId  } })
                    .then(res => {
                        if(res.data.length > 0) {
                            node.children = res.data;
                        }
                    }).catch(e => {
                    this.$Message.error("查询失败");
                });
            },
            async selectMenu(name){
                if(name == "1_0") {
                    this.filePath = this.recentlyVieweds[0].filePath;
                    this.fileName = this.recentlyVieweds[0].fileName;
                    this.fileId = this.recentlyVieweds[0].fileId;
                }else if(name == "1_1") {
                    this.filePath = this.recentlyVieweds[1].filePath;
                    this.fileName = this.recentlyVieweds[1].fileName;
                    this.fileId = this.recentlyVieweds[1].fileId;
                }else if(name == "1_2") {
                    this.filePath = this.recentlyVieweds[2].filePath;
                    this.fileName = this.recentlyVieweds[2].fileName;
                    this.fileId = this.recentlyVieweds[2].fileId;
                }else if(name == "1_3") {
                    this.filePath = this.recentlyVieweds[3].filePath;
                    this.fileName = this.recentlyVieweds[3].fileName;
                    this.fileId = this.recentlyVieweds[3].fileId;
                }else if(name == "1_4") {
                    this.filePath = this.recentlyVieweds[4].filePath;
                    this.fileName = this.recentlyVieweds[4].fileName;
                    this.fileId = this.recentlyVieweds[4].fileId;
                }else if(name == "2"){
                    this.loading = true;
                    this.fileName = "";
                    this.filePath = "";
                    this.fileId = "";
                    this.levelArray.splice(0,this.levelArray.length);
                    await this.queryTree(this.treeData[0]);
                    this.currentNodeArray = this.treeData[0].children;
                    this.pdfDatas.splice(0,this.pdfDatas.length);
                    this.videoDatas.splice(0,this.videoDatas.length);
                    this.loading = false;
                    this.levelArray = [{
                        title:"资料列表",
                        categoryId:"0",
                        parentId:"0"
                    }]
                }else if(name == "3"){
                    this.levelArray = [{
                        title:"我的收藏",
                        categoryId:"",
                        parentId:""
                    }]
                }else{
                    let index = name.split("_")[1];
                    this.fileId = this.collectionFiles[index].fileId;
                    this.filePath = this.collectionFiles[index].filePath;
                    this.fileName = this.collectionFiles[index].fileName;
                    this.collectedId = this.collectionFiles[index].id;
                    this.isCollected = true;
                }
            },
            async toLevelItem(index){
                this.loading = true;
                await this.queryTree(this.levelArray[index]);
                this.currentNodeArray = this.levelArray[index].children;
                this.pdfDatas.splice(0,this.pdfDatas.length);
                this.videoDatas.splice(0,this.videoDatas.length);
                await this.queryPdf(this.levelArray[index].categoryId);
                await this.queryVideo(this.levelArray[index].categoryId);
                this.levelArray.splice(index+1,this.levelArray.length-index-1);
                this.loading = false;
            },
            async enterDir(node){
                this.loading = true;
                this.levelArray.push({parentId:node.parentId,categoryId:node.categoryId,title:node.title});
                await this.queryTree(node);
                this.currentNodeArray = node.children;
                this.pdfDatas.splice(0,this.pdfDatas.length);
                this.videoDatas.splice(0,this.videoDatas.length);
                await this.queryPdf(node.categoryId);
                await this.queryVideo(node.categoryId);
                this.loading = false;
            },
            enterVideo(node){
                this.isCollected = false;
                this.collectionFiles.forEach(item=>{
                    if(item.fileId == node.fileId) {
                        this.isCollected = true;
                        this.collectedId = item.id;
                    }
                })
                this.fileId = node.fileId;
                this.fileName = node.fileName;
                this.filePath = Api.viewPicture + node.filePath;
                this.recentlyVieweds.unshift({
                    fileName:node.fileName,
                    filePath:Api.viewPicture + node.filePath
                })
                if(this.recentlyVieweds.length > 5){
                    this.recentlyVieweds.slice(5,1);
                }
            },
            enterPdf(node){
                this.isCollected = false;
                this.collectionFiles.forEach(item=>{
                    if(item.fileId == node.fileId) {
                        this.isCollected = true;
                        this.collectedId = item.id;
                    }
                })
                this.fileId = node.fileId;
                this.fileName = node.fileName;
                this.filePath = "./pdf/web/viewer.html?file=" + Api.downloadMongoFile + "/" + node.fileId+ "#" + node.fileName;
                this.recentlyVieweds.unshift({
                    fileName:node.fileName,
                    filePath:"./pdf/web/viewer.html?file=" + Api.downloadMongoFile + "/" + node.fileId+ "#" + node.fileName
                })
                if(this.recentlyVieweds.length > 5){
                    this.recentlyVieweds.slice(5,1);
                }
            },
            async returnTo(){
                if(this.filePath != ""){
                    this.filePath = "";
                    this.fileName = "";
                    this.fileId = "";
                }
                else if( this.levelArray.length > 1){
                    this.loading = true;
                    var node = {categoryId:this.levelArray[this.levelArray.length-1].parentId,children:[]};
                    await this.queryTree(node);
                    this.currentNodeArray = node.children;
                    this.pdfDatas.splice(0,this.pdfDatas.length);
                    this.videoDatas.splice(0,this.videoDatas.length);
                    await this.queryPdf(this.levelArray[this.levelArray.length-1].parentId);
                    await this.queryVideo(this.levelArray[this.levelArray.length-1].parentId);
                    this.levelArray.splice(this.levelArray.length-1,1);
                    this.loading = false;
                }
            },
            async queryVideo(id) {
                let data = {
                    page: 1,
                    rows: 1000,
                    categoryId: id,
                    type: "video"
                };
                await this.$http
                    .get(Api.trainingInfo, {
                        params: data
                    })
                    .then(res => {
                        this.videoDatas = res.data.data;
                    })
                    .catch(e => {
                        this.$Message.error("请求失败");
                    });
            },
            async queryPdf(id) {
                let data = {
                    page: 1,
                    rows: 1000,
                    categoryId: id,
                    type: "pdf"
                };
                await this.$http
                    .get(Api.trainingInfo, {
                        params: data
                    })
                    .then(res => {
                        this.pdfDatas = res.data.data;
                    })
                    .catch(e => {
                        this.$Message.error("请求失败");
                    });
            },
            queryFileToCollection(){
                this.$http
                    .get(Api.trainingFileToCollection + "/"  + sessionStorage("userId").getObject("userId").userId)
                    .then(res => {
                        if(res.data.status == 200) {
                            this.collectionFiles = res.data.data;
                        }else{
                            this.$Message.error({
                                content: "查询我的收藏失败",
                                duration: 4
                            });
                        }
                    })
                    .catch(e => {
                        this.$Message.error({
                            content: "查询我的收藏失败",
                            duration: 4
                        });
                    });
            },
            addFileToCollection(){
                this.fileLoading = true;
                let data = {
                    id:this.uuid(),
                    fileId:this.fileId,
                    filePath:this.filePath,
                    fileName:this.fileName,
                    userId: sessionStorage("userId").getObject("userId").userId
                }
                this.$http
                    .post(Api.trainingFileToCollection, data)
                    .then(res => {
                        if(res.data.status == 200) {
                            this.$Message.success({
                                content: "添加收藏成功",
                                duration: 4
                            });
                            this.isCollected = true;
                            this.collectionFiles.push(data);
                        }else{
                            this.$Message.error({
                                content: "添加收藏失败",
                                duration: 4
                            });
                        }
                        this.fileLoading = false;
                    })
                    .catch(e => {
                        this.$Message.error({
                            content: "添加收藏失败",
                            duration: 4
                        });
                    });
            },
            removeFileToCollection(){
                this.fileLoading = true;
                this.$http
                    .delete(Api.trainingFileToCollection + "/" + this.collectedId)
                    .then(res => {
                        if(res.data.status == 200) {
                            this.$Message.success({
                                content: "删除收藏成功",
                                duration: 4
                            });
                            let index = 0;
                            for(;index <this.collectionFiles.length;index++){
                                if(this.collectionFiles[index].id == this.collectedId)
                                    break;
                                index++;
                            }
                            this.collectionFiles.splice(index,1);
                        }else{
                            this.$Message.error({
                                content: "删除收藏失败",
                                duration: 4
                            });
                        }
                        this.fileLoading = false;
                    })
                    .catch(e => {
                        this.$Message.error({
                            content: "删除收藏失败",
                            duration: 4
                        });
                    });
            },
            uuid() {
                let s = [];
                let hexDigits = "0123456789abcdef";
                for (let i = 0; i < 32; i++) {
                    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
                }
                s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
                s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
                let uuid = s.join("");
                return uuid;
            },
        }
    }
</script>

<style>
.trainingDivClass{
    cursor: pointer;
    display:flex;
    flex-direction: column;
    justify-content:center;
    align-items:center;
    width:100%;
    color:white;
}


    .titleClass{
        font-size: 14px;
        font-family: HiraginoSansGB-W6, HiraginoSansGB;
        font-weight: normal;
        color: black;
        line-height: 27px;
        letter-spacing: 1px;
        margin-bottom:10px;
        width:120px;
        text-align: center;
    }

    .shiPinShouCeClass{
        display: flex;
        width: 120px;
        flex-direction: row;
        justify-content: space-between;
    }

    .contentClass{
        font-size: 14px;
        font-family: HiraginoSansGB-W3, HiraginoSansGB;
        font-weight: normal;
        color: #FFFFFF;
        line-height: 21px;
    }

    .navigationClass{
        line-height: 20px;
        margin-left:10px;
    }

    .navigationClass:hover{
        cursor: pointer;
        background-color: #40C4FF;
    }
</style>